// 引入mongoose第三方模块
const mongoose = require('mongoose');
// 验证对象字段模块
const Joi = require('joi');
// 引入加密模块
const bcrypt = require('bcrypt');
// 创建用户集合规则
const userSchema = mongoose.Schema({
  username: {
    type: String,
    required: true,
    minlength: 2,
    maxlength: 20
  },
  email: {
    type: String,
    unique: true,// 保证邮箱在插入数据库不重复
  },
  password: {
    type: String,
    required: true
  },
  // admin：超级管理员
  // normal: 普通用户
  role: {
    type: String,
    required: true,
  },
  // 0: 启用状态
  // 1: 禁用状态
  state: {
    type: Number,
    default: 0
  }
})

// 创建集合
const User = mongoose.model('User', userSchema);

async function createUser(){
  const salt = await bcrypt.genSalt(10);
  const pass = await bcrypt.hash('123456', salt);
  const user = await User.create({
    username: 'yibo',
    email: 'yibo@qq.com',
    password: pass,
    role: 'admin',
    state: 0
  });
  console.log(user);
  
}

// 验证用户信息
const validateUser = (user) => {
    // 定义对象的验证规则
    const schema = {
      username: Joi.string().min(2).max(12).required().error(new Error('用户名不符合规则')),
      email: Joi.string().email().error(new Error('邮箱不符合要求')),
      password: Joi.string().regex(/^\w{3,30}$/).error(new Error('密码不符合要求')),
      role: Joi.string().valid('normal', 'admin').required().error(new Error('角色值非法')),
      state: Joi.number().valid(0, 1).required().error(new Error('状态值规则'))
    };
    return Joi.validate(user, schema);
}

// createUser();
// 将用户集合作为模块成员进行导出
module.exports = {
  User,
  validateUser
}